// lib/services/product_api.dart
import 'package:multi_shop/network/api_client.dart';
import 'package:multi_shop/network/api_routes.dart';
import 'package:multi_shop/models/product.dart';
import 'package:multi_shop/models/category.dart';

class ProductApi {
  final _http = HttpClient();

  Future<List<Product>> list({
    int page = 1,
    int? categoryId,
    String? keyword,
    int? merchantId,
  }) {
    return _http.getJson<List<Product>>(
      ApiRoutes.products,
      query: {
        'page': page,
        'categoryId': categoryId,
        'keyword': keyword,
        'merchantId': merchantId,
      },

      convert: (data) {
        final list = data["list"] as List;
        return list
            .map((e) => Product.fromJson(Map<String, dynamic>.from(e as Map)))
            .toList();
      },
    );
  }

  Future<Product> detail(int id) {
    return _http.getJson<Product>(
      ApiRoutes.getProductDetail,
      query: {'id': id},
      convert: (data) {
        final root = Map<String, dynamic>.from(data as Map);
        final goods = Map<String, dynamic>.from(root['goods'] as Map);
        return Product.fromJson(goods);
      },
    );
  }

  Future<List<Category>> categories() {
    return _http.getJson<List<Category>>(
      ApiRoutes.getCategory,
      convert: (data) {
        final list = data["list"] as List;
        return list
            .map((e) => Category.fromJson(Map<String, dynamic>.from(e)))
            .toList();
      },
    );
  }

  Future<void> addToCart({required String productId, int quantity = 1}) {
    return _http.postJson<void>(ApiRoutes.cartAdd, {
      'productId': productId,
      'quantity': quantity,
    });
  }
}
